import config.config
from widgets.scriptWidgets.ScriptWidget import ScriptWidget
from PySide6.QtWidgets import QLabel, QComboBox, QPushButton, QFileDialog
from PySide6.QtGui import QPixmap
from enums.WidgetType import WidgetType
from enums.ZhButtonType import ZhButtonType
from enums.ButtonType import ButtonType
from ..ScriptTimeInput import ScriptTimeInput
from widgets.scriptWidgets.ScriptInput import ScriptInput
from util.Mouse import MouseUtil
from PIL import ImageGrab, ImageQt
import time
import os.path as ospath
import shutil


class LongPressPic(ScriptWidget):
    def __init__(self, initType=None):
        super().__init__(WidgetType.LONG_PRESS_PIC)
        self.picPath = ospath.join(
            config.config.SCRIPT_PIC_RECOGNITION_PIC_PATH,
            str(int(round(time.time() * 1000))) + '.png'
        )
        self.initType = initType

        self.labTitle = QLabel(self)
        self.labTitle.setText('长按图片:')

        self.labTitle.setToolTip('在指定区域内识别并单击图片')

        self.labTitle.setFixedSize(55, self.lineHeight)
        self.addWidget(self.labTitle)

        self.newLineSpaceWidth = self.labTitle.width() + self.intervalX

        # x
        self.inputX = ScriptInput(self, 'x')
        self.inputX.text = 0
        self.addWidget(self.inputX)

        # y
        self.inputY = ScriptInput(self, 'y')
        self.inputY.text = 0
        self.addWidget(self.inputY)

        # buttonType
        self.comButtonType = QComboBox(self)
        self.comButtonType.addItems(ZhButtonType.values())
        self.comButtonType.setCurrentText(ZhButtonType.values()[0])
        self.addWidget(self.comButtonType)

        if initType == 'edit' or initType == 'create':
            self.addOperate()

        # 宽
        self.inputWidth = ScriptInput(self, '宽')
        self.inputWidth.text = 0
        self.addWidget(self.inputWidth)

        # 高
        self.inputHeight = ScriptInput(self, '高')
        self.inputHeight.text = 0
        self.addWidget(self.inputHeight)

        self.btnTrack = QPushButton(self)
        self.btnTrack.setText('选择区域')
        self.btnTrack.clicked.connect(self.startAreaChoose)
        self.addWidget(self.btnTrack)

        self.newLine()
        # 图片
        self.labImgTitle = QLabel('图片', self)
        self.labImgTitle.setFixedSize(30, self.lineHeight)
        self.addWidget(self.labImgTitle)

        self.labImg = QLabel(self)
        self.labImg.setFixedSize(self.lineHeight, self.lineHeight)
        self.labImg.setStyleSheet(
            "QLabel{background:white;}"
        )
        self.addWidget(self.labImg)

        self.btnChoosePic = QPushButton(self)
        self.btnChoosePic.setText('选择图片')
        self.btnChoosePic.clicked.connect(self.choosePic)
        self.addWidget(self.btnChoosePic)

        self.btnGrab = QPushButton(self)
        self.btnGrab.setText('截取屏幕')
        self.btnGrab.clicked.connect(self.startGrab)
        self.addWidget(self.btnGrab)

        self.inputTime = ScriptTimeInput(self, '时间')
        self.addWidget(self.inputTime)

    def choosePic(self):
        imgName, imgType = QFileDialog.getOpenFileName(
            self, "选择图片", "",
            "Image Files (*.png *.jpeg *.bmp);;All Files(*)")
        if imgName is None or imgName == '':
            return

        # 将需要识别的图片保存到应用内部存储地址
        shutil.copy(imgName, self.picPath)

        self.labImg.setPixmap(QPixmap(imgName).scaled(self.labImg.width(), self.labImg.height()))

    def onMouseClick(self, x, y, width, height, button):
        self.inputX.text = x
        self.inputY.text = y
        self.inputWidth.text = width
        self.inputHeight.text = height
        buttonName = button.name.upper()
        self.comButtonType.setCurrentText(ZhButtonType[buttonName].value)

    def startAreaChoose(self):
        MouseUtil.listenArea(self.onMouseClick)

    def grabScreen(self, x, y, width, height, button):
        left = x
        top = y
        right = x + width
        bottom = y + height
        # 将需要识别的图片保存到应用内部存储地址
        recoImg = ImageGrab.grab(bbox=(left, top, right, bottom))
        recoImg.save(self.picPath)
        self.labImg.setPixmap(ImageQt.toqpixmap(recoImg))

    def startGrab(self):
        MouseUtil.listenArea(self.grabScreen)

    @property
    def data(self):
        zhType = ZhButtonType(self.comButtonType.currentText())
        buttonType = ButtonType[zhType.name].value
        return {
            'type': self.type.value,
            'x': int(self.inputX.text),
            'y': int(self.inputY.text),
            'width': int(self.inputWidth.text),
            'height': int(self.inputHeight.text),
            'button': buttonType,
            'pic': self.picPath,
            'time': int(self.inputTime.text),
            'enable': self.switchEnable.isChecked()
        }

    @data.setter
    def data(self, data):
        self.inputX.text = str(data['x'])
        self.inputY.text = str(data['y'])
        self.inputWidth.text = str(data['width'])
        self.inputHeight.text = str(data['height'])
        self.comButtonType.setCurrentText(ZhButtonType[data['button'].upper()].value)
        self.labImg.setPixmap(QPixmap(data['pic']))
        self.inputTime.text = str(data['time'])
        self.picPath = data['pic']
